package com.coder.oj.admin.controller;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.coder.oj.admin.dto.LoginDto;
import com.coder.oj.admin.mapstruct.AdminMapstruct;
import com.coder.oj.admin.vo.LoginVo;
import com.coder.oj.common.core.R;
import com.coder.oj.common.entity.Admin;
import com.coder.oj.common.enums.CommonStatusEnum;
import com.coder.oj.common.exception.DataException;
import com.coder.oj.common.mapper.AdminMapper;
import com.coder.oj.common.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Api(tags = {"登录接口"})
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private AdminMapstruct adminMapstruct;

    @PostMapping
    @ApiOperation("执行登录")
    public R<LoginVo> login(@Validated @RequestBody LoginDto loginDto) {
        Admin admin = new LambdaQueryChainWrapper<>(adminMapper)
                .eq(Admin::getStatus, CommonStatusEnum.ENABLED.getValue())
                .eq(Admin::getUsername, loginDto.getUsername())
                .eq(Admin::getPassword, DigestUtils.md5Hex(loginDto.getPassword()))
                .one();
        if(ObjectUtils.isEmpty(admin)) {
            throw new DataException("用户名或密码错误");
        }
        LoginVo vo = new LoginVo();
        vo.setToken(JwtUtil.sign(admin.getId()));
        vo.setAdminInfo(adminMapstruct.toVO(admin));
        return R.ok().setResult(vo);
    }
}
